<?php 
class Country_Model_Poll extends Core_Model_Item_Abstract{
    
   public function getRichContent() {
        $view = new Zend_View();
        return $view->partial('_displayQuestionpoll.tpl', 'country', array('item' => $this, 'options' => $this->getOptions(), 'isFeed' => true));
   }             
    
   public function getUserVoted($user_id,$country_id){
        $voteTable = Engine_Api::_()->getDbtable('pollvotes','country');
        $select = $voteTable->select()
                            ->where('poll_id =?',$this->getIdentity())
                            ->where('country_id = ?',$country_id)
                            ->where('user_id = ?',$user_id);
        $rows = $voteTable->fetchAll($select);
        
        $result = array();
        foreach ($rows as $vote){
            $result[] = $vote->polloption_id;
        }
        return $result;
   }
   public function getVote($user_id,$country_id){
        $voteTable = Engine_Api::_()->getDbtable('pollvotes','country');
        $select = $voteTable->select()
                            ->where('country_id = ?',$country_id)
                            ->where('poll_id = ?',$this->getIdentity())
                            ->where('user_id = ?',$user_id);
        $row = $voteTable->fetchRow($select);
        return $row;
    }
    
    
    
    public function hasVote($user_id, $country_id){
        $row = $this->getVote($user_id, $country_id);
        if (!empty($row)) return true;
        return false;
    }
    
    public function setVote($user_id,$option_id,$country_id){
        $voteTable = Engine_Api::_()->getDbtable('pollvotes','country');
        $row = $voteTable->createRow();
        $row->user_id = $user_id;
        $row->country_id = $country_id;
        $row->polloption_id = $option_id;
        $row->save();
        
        $pollOption = Engine_Api::_()->getItem('polloption',$option_id);
        if (!empty($pollOption)) {
            $pollOption->votecount = $pollOption->votecount + 1;
            $pollOption->save();
        }
    }
    
    public function getOptions(){
        $pollOptios = Engine_Api::_()->getDbtable('polloptions','country');
        return $pollOptios->getPollOptions($this->getIdentity());
        
    }
    
    public function deleteOptions(){
        $pollOptios = Engine_Api::_()->getDbtable('polloptions','country');
        return $pollOptios->deletePollOptions($this->getIdentity());
    }
    public function getVoteCount($country_id){
        
        $voteT = Engine_Api::_()->getDbtable('pollvotes','country');
        $select = $voteT->select()
                        ->where('country_id = ?',$country_id)
                        ->where('poll_id = ?',$this->poll_id);
        $rows = $voteT->fetchAll($select);
        
        if ($rows) return count($rows);
        return 0;
        
        
    }
}
?>